package cn.glutnn.controller;

import cn.glutnn.entity.AdminUser;
import cn.glutnn.entity.Result;
import cn.glutnn.entity.dto.LoginDTO;
import cn.glutnn.service.AdminUserService;
import cn.glutnn.utils.JwtUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * @author msh
 * @date 2025/04/04
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private AdminUserService adminUserService;
    
    /**
     * 登录接口
     * @param loginDTO 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result login(@Valid @RequestBody LoginDTO loginDTO) {
        try {
            // 认证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword())
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 获取UserDetails
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            
            // 获取管理员用户信息
            AdminUser adminUser = adminUserService.findByUsername(loginDTO.getUsername());
            
            // 更新最后登录时间
            adminUser.setLastLoginTime(LocalDateTime.now());
            adminUserService.updateById(adminUser);
            
            // 生成token
            String token = jwtUtil.generateToken(userDetails.getUsername(), adminUser.getId());
            
            // 构造返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("userInfo", adminUser);
            
            return Result.success("登录成功", result);
        } catch (Exception e) {
            return Result.error("用户名或密码错误");
        }
    }
} 